﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Device.Location;
using System.Web.Security;
using Be;
using DayPilot.Utils;
using DayPilot.Web.Ui.Enums;
using DayPilot.Web.Ui.Events;
using DayPilot.Web.Ui.Events.Bubble;
using WebGui.BllBookingService;
using WebGui.BllLessonService;

namespace WebGui.User {
    /// <summary>
    /// This class is used to show all bookings.
    /// </summary>
    public partial class Booking : Page {
        /// <summary>
        /// The Booking service client
        /// </summary>
        private BookingServiceClient _booking;
        /// <summary>
        /// The Lesson Service Client
        /// </summary>
        private LessonServiceClient _lesson;
        /// <summary>
        /// The Bookings color in the calender
        /// </summary>
        private string _BookingsColor = "#808080";
        /// <summary>
        /// the Lessons color in the calender
        /// </summary>
        private string _LessonsColor = "#C2C2C2";
        /// <summary>
        /// Cell background color
        /// </summary>
        private string _CellBackGround = "#D9D9D9";
        /// <summary>
        /// Loads the page. 
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The event Arguments</param>
        protected void Page_Load(object sender, EventArgs e) {
            try {
                _lesson = (LessonServiceClient) Session["Lesson"];
                _booking = (BookingServiceClient) Session["Booking"];
                if(!IsPostBack) {
                    CalBookings.StartDate = Week.FirstDayOfWeek();
                    LoadBookings();
                    DdlUser.DataSource = Roles.GetUsersInRole("kørelære");
                    DdlUser.DataBind();

                }
            } catch(Exception ex) {
                ShowMessage(ex.Message);
            }
        }
     /// <summary>
     /// Loads all booking in to the navigator and calender
     /// </summary>
        private void LoadBookings() {
            try {
                Session["Lessons"] = _lesson.GetEvents(CalBookings.StartDate, CalBookings.Days);
                List<BeBooking> calendarbookings = _booking.GetBookingsWeek(CalBookings.StartDate, CalBookings.Days);
                List<BeBooking> elevbookings = new List<BeBooking>();
                foreach(BeBooking booking in calendarbookings) {
                    if(booking.UserId == Membership.GetUser().ProviderUserKey.ToString()) {
                        elevbookings.Add(booking);
                    }
                }
                CalBookings.DataSource = elevbookings;
                CalBookings.DataBind();
                elevbookings.Clear();
                int navEnd = (int) (CalNavigator.VisibleEnd - CalNavigator.VisibleStart).TotalDays;
                List<BeBooking> navigatorbookings = _booking.GetBookingsWeek(CalNavigator.VisibleStart, navEnd);
                foreach(BeBooking booking in navigatorbookings) {
                    if(booking.UserId == Membership.GetUser().ProviderUserKey.ToString()) {
                        elevbookings.Add(booking);
                    }
                }
                CalNavigator.DataSource = elevbookings;
                CalNavigator.DataBind();

            } catch(Exception ex) {
                ShowMessage(ex.Message);
            }
        }

        /// <summary>
        /// Show a message in a javascript alert box
        /// </summary>
        /// <param name="message">The message to show</param>
        private void ShowMessage(string message) {
            Response.Write("<script type='text/javascript'>alert('" + message + "'); </script>");
        }
        /// <summary>
        /// This moves the booking with drag and drop
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The event Arguments</param>
        protected void CalBookings_EventMove(object sender, EventMoveEventArgs e) {
            try {
                int id = Convert.ToInt32(e.Value);
                BeBooking bebooking = _booking.GetBookingFromId(id);
                string teacherId = Membership.GetUser(DdlUser.SelectedValue).ProviderUserKey.ToString();
                bebooking.TeacherId = teacherId;
                BeLesson lesson = _lesson.LessonPresents(bebooking);
                BeBooking booking = new BeBooking(bebooking.Id, e.NewStart, e.NewEnd, bebooking.StartLatitude, bebooking.StartLongitude, bebooking.EndLatitude, bebooking.EndLongitude, bebooking.UserId, teacherId, lesson.Id);
                _booking.EditBooking(booking);
                LoadBookings();
                CalBookings.Update();
            } catch(Exception ex) {
                ShowMessage(ex.Message);
            }
        }
        /// <summary>
        /// this is used to navigat in the calender
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The event Arguments</param>
        protected void CalBookings_Command(object sender, DayPilot.Web.Ui.Events.CommandEventArgs e) {
            try
            {
                switch (e.Command)
                {
                    case "previous":
                        CalBookings.StartDate = CalBookings.StartDate.AddDays(-7);
                        LoadBookings();
                        CalBookings.DataBind();
                        CalBookings.Update(CallBackUpdateType.Full);
                        break;
                    case "navigate":
                        DateTime start = (DateTime)e.Data["start"];
                        CalBookings.StartDate = start;
                        LoadBookings();
                        CalBookings.Update(CallBackUpdateType.Full);
                        break;
                    case "refresh":
                        LoadBookings();
                        CalBookings.Update();
                        break;
                }
            }
            catch (Exception ex) { ShowMessage(ex.Message); }
        }
        /// <summary>
        /// The navigator controller.
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The event Arguments</param>
        protected void CalNavigator_VisibleRangeChanged(object sender, DayPilot.Web.Ui.Events.Navigator.VisibleRangeChangedEventArgs e) {
                LoadBookings();
        }
        /// <summary>
        /// menu click envork
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The event Arguments</param>
        protected void CalBookings_EventMenuClick(object sender, EventMenuClickEventArgs e) {
            try
            {
                if (e.Command == "Delete")
                {
                    int id = Convert.ToInt32(e.Value);
                    var target = _booking.GetBookingFromId(id);
                    if (target != null)
                    {
                        BeBooking booking = new BeBooking(id);
                        _booking.DeleteBooking(booking, Roles.GetRolesForUser().ToString());
                    }
                    LoadBookings();
                    CalBookings.DataBind();
                    CalBookings.Update();
                }
            }
            catch (Exception ex) { ShowMessage(ex.Message); }
        }
        /// <summary>
        /// Resizeing a booking
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The event Arguments</param>
        protected void CalBookings_EventResize(object sender, EventResizeEventArgs e) {
            try {
                int id = Convert.ToInt32(e.Value);
                BeBooking bebooking = _booking.GetBookingFromId(id);
                string teacherId = Membership.GetUser(DdlUser.SelectedValue).ProviderUserKey.ToString();
                bebooking.TeacherId = teacherId;
                BeLesson lesson = _lesson.LessonPresents(bebooking);
                BeBooking booking = new BeBooking(bebooking.Id, e.NewStart, e.NewEnd, bebooking.StartLatitude, bebooking.StartLongitude, bebooking.EndLatitude, bebooking.EndLongitude, bebooking.UserId, teacherId, lesson.Id);
                _booking.EditBooking(booking);
                LoadBookings();
                CalBookings.Update();
            } catch(Exception ex) {
                ShowMessage(ex.Message);
            }
        }
        /// <summary>
        /// Deleting a booking by click in corner 
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The event Arguments</param>
        protected void CalBookings_EventDelete(object sender, EventDeleteEventArgs e) {
            try {
                int id = Convert.ToInt32(e.Value);
                BeBooking booking = _booking.GetBookingFromId(id);
                string str = _booking.DeleteBooking(booking, "elev");
                LoadBookings();
                CalBookings.Update();

            } catch(Exception ex) {
                ShowMessage(ex.Message);
            }
        }
        /// <summary>
        /// When selecting a booking this is called and updates the calender.
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The event Arguments</param>
        protected void CalBookings_EventSelect(object sender, DayPilotEventArgs e) {
            CalBookings.Update();
        }
        /// <summary>
        /// Buildes the strings in the load 
        /// bubble in left coner of the calender
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The event Arguments</param>
        protected void DayPilotBubble_RenderContent(object sender, DayPilot.Web.Ui.Events.Bubble.RenderEventArgs e) {
            if(e is RenderEventBubbleEventArgs) {
                RenderEventBubbleEventArgs re = e as RenderEventBubbleEventArgs;
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("<b>{0}</b><br />", re.Text);
                sb.AppendFormat("Start: {0}<br />", re.Start);
                sb.AppendFormat("End: {0}<br />", re.End);
                sb.AppendFormat("<br />");
                sb.AppendFormat("<b>Double-click the event to enter inline edit mode.</b>");
                re.InnerHTML = sb.ToString();
            } else if(e is RenderTimeBubbleEventArgs) {
                RenderTimeBubbleEventArgs re = e as RenderTimeBubbleEventArgs;
                e.InnerHTML = "<b>Time header details</b><br />From:" + re.Start + "<br />To: " + re.End;
            } else if(e is RenderCellBubbleEventArgs) {
                RenderCellBubbleEventArgs re = e as RenderCellBubbleEventArgs;
                e.InnerHTML = "<b>Cell details</b><br />Column:" + re.ResourceId + "<br />From:" + re.Start + "<br />To: " + re.End;
            }
        }
        /// <summary>
        /// sets colors of bookings.
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The event Arguments</param>
        protected void CalBookings_BeforeEventRender(object sender, DayPilot.Web.Ui.Events.Calendar.BeforeEventRenderEventArgs e) {
            e.BackgroundColor = _BookingsColor;
            e.DurationBarColor = _BookingsColor;
        }
        /// <summary>
        /// Sets the color on background cells and lessons
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The event Arguments</param>
        protected void CalBookings_BeforeCellRender(object sender, BeforeCellRenderEventArgs e) {
            try
            {
                e.BackgroundColor = _CellBackGround;
                List<BeLesson> lessons = (List<BeLesson>)Session["Lessons"];
                foreach (BeLesson lesson in lessons)
                {
                    if (e.End <= lesson.EndTime && e.Start >= lesson.StartTime && Membership.GetUser(DdlUser.SelectedValue).ProviderUserKey.ToString() == lesson.UserId)
                    {
                        e.BackgroundColor = _LessonsColor;
                    }
                }
            }
            catch (Exception ex) { ShowMessage(ex.Message); }
        }
        /// <summary>
        /// Loads the lesson for a driving instructor
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The event Arguments</param>
        protected void DdlUser_SelectedIndexChanged(object sender, EventArgs e) {
            LoadBookings();
        }
    }
}